package com.tuo51.manager.controller;


import com.tuo51.foudation.exception.BusinessException;
import com.tuo51.foudation.model.ErrorCode;
import com.tuo51.foudation.model.MemVerificationCache;
import com.tuo51.foudation.model.StatusResponse;
import com.tuo51.manager.aop.OperationLogAnnotation;
import com.tuo51.manager.domain.Dealer;
import com.tuo51.manager.repository.DealerRepository;
import com.tuo51.manager.vo.DealerVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import static com.tuo51.foudation.constant.RequestConstant.TICKET;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

/**
 * 附近的合作伙伴
 */
@RestController
@RequestMapping("/mapi/dealer")
@Api(value = "/mapi/dealer", tags = "OP - 经销商管理")
public class MAPIDealerController {

    @Autowired
    DealerRepository itemRepository;


    @Autowired
    MemVerificationCache cache;

    @RequestMapping(value = "/list", method = GET)
    @ApiOperation(value = "查询列表")
    public StatusResponse userlist(@RequestHeader(TICKET) String ticket){

        String staffId = cache.getStaffId(ticket);

        return StatusResponse.success(itemRepository.findAllByOrderByCreatedDesc());
    }

    @OperationLogAnnotation(operModul = "经销商",operType = "编辑",operDesc = "编辑或新增")
    @RequestMapping(value = "/edit", method = POST)
    @ApiOperation(value = "编辑")
    public StatusResponse editStaff(@RequestHeader(TICKET) String ticket,
                                    DealerVO channel){

        Dealer ret = null;
        if (StringUtils.isNotEmpty(channel.getId())){
            ret = itemRepository.getOne(channel.getId());
        }else{
            ret = new Dealer();
        }

        if (ret == null){
            throw new BusinessException(ErrorCode.MATERIAL_NOT_EXIST, "条目不存在");
        }

        ret.setComment(channel.getComment());
        ret.setName(channel.getName());
        ret.setPhone(channel.getPhone());

        itemRepository.save(ret);

        return StatusResponse.success(ret);
    }
}
